package com.app.scale.video;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.SurfaceTexture;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;

import com.app.scale.R;
import com.app.scale.util.ThreadUtils;
import com.hikvision.open.hikvideoplayer.HikVideoPlayer;
import com.hikvision.open.hikvideoplayer.HikVideoPlayerCallback;
import com.hikvision.open.hikvideoplayer.HikVideoPlayerFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import my.LogUtil;

public class CustomVideo extends FrameLayout {

//    @BindView(R.id.video_view)
//    IjkVideoView videoView;
    @BindView(R.id.video_view)
    TextureView videoView;
    //    @BindView(R.id.img_icon)
//    ImageView img_icon;
    @BindView(R.id.view_main)
    FrameLayout view_main;


    FrameLayout base_layout;
    String play_url;

    private Context mContext;
    HikVideoPlayer mPlayer;
    private boolean isFullSreen = false;
    private boolean isBig = false;

    int screenWidth = 0;
    int screenHeight = 0;


    @SuppressLint("NewApi")
    public CustomVideo(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

    }

    public CustomVideo(Context context) {
        super(context);
    }

    public CustomVideo(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    void init(Context context) {
        mContext = context;
        base_layout = (FrameLayout) LayoutInflater.from(context).inflate(R.layout.video_custom_video_view, this, true);
        ButterKnife.bind(this, base_layout);
        if (mPlayer == null) {
            mPlayer = HikVideoPlayerFactory.provideHikVideoPlayer();
            //设置默认值
            mPlayer.setHardDecodePlay(false);
            mPlayer.setSmartDetect(true);
        }
        videoView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//                LogUtil.i("onSurfaceTextureAvailable---width->" + width + "-----height--" + height);
                mPlayer.setSurfaceTexture(surface);
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                LogUtil.i("onSurfaceTextureDestroyed-");
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

            }
        });
    }


    public void setData(String url, boolean isSeleted) {
        if(TextUtils.isEmpty(url)){
            play_url = null;
            stopPlay();
        }else {
            if(!TextUtils.isEmpty(play_url) && !play_url.equals(url)){
                stopPlay();
            }

            if(TextUtils.isEmpty(play_url) || !play_url.equals(url)){
                play_url = url;
                initData();
            }

        }

        if (isSeleted) {
            view_main.setBackgroundResource(R.drawable.video_seleted_bg);
        } else {
            view_main.setBackgroundColor(getResources().getColor(R.color.black));
        }
    }

    public void initData() {
        if (TextUtils.isEmpty(play_url)) {
            if (mPlayer != null) {
                mPlayer.stopPlay();
            }
//            if(videoView.isPlaying()){
//                videoView.stopPlayback();
//            }
            return;
        }

//        videoView.setVideoURI(Uri.parse(play_url));
//        videoView.start();
        if (mPlayer == null) {
            mPlayer = HikVideoPlayerFactory.provideHikVideoPlayer();
        }
        if(videoView.getSurfaceTexture() != null){
            ThreadUtils.doOnThread(new ThreadUtils.ThreadTask() {
                @Override
                public void doOnThread() {
                    mPlayer.startRealPlay(play_url, new HikVideoPlayerCallback() {
                        //播放结果回调
                        // status 共三种状态：SUCCESS（播放成功）、FAILED（播放失败）、EXCEPTION（取流异常）
                        // 错误码，只有 FAILED 和 EXCEPTION 才有值
                        // 注意：回调仍为子线程
                        @Override
                        public void onPlayerStatus(@NonNull HikVideoPlayerCallback.Status status, int errorCode) {
                            LogUtil.i("onPlayerStatus--->status----" + status.name() + "---errorCode--" + errorCode);
                        }
                    });
                }
            });
        }else {
            // 设置播放画面显示surface,仅支持TextureView
            videoView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
                @Override
                public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//                LogUtil.i("onSurfaceTextureAvailable---width->" + width + "-----height--" + height);
                    mPlayer.setSurfaceTexture(surface);
                    ThreadUtils.doOnThread(new ThreadUtils.ThreadTask() {
                        @Override
                        public void doOnThread() {
                            mPlayer.startRealPlay(play_url, new HikVideoPlayerCallback() {
                                //播放结果回调
                                // status 共三种状态：SUCCESS（播放成功）、FAILED（播放失败）、EXCEPTION（取流异常）
                                // 错误码，只有 FAILED 和 EXCEPTION 才有值
                                // 注意：回调仍为子线程
                                @Override
                                public void onPlayerStatus(@NonNull HikVideoPlayerCallback.Status status, int errorCode) {
                                    LogUtil.i("onPlayerStatus--->status----" + status.name() + "---errorCode--" + errorCode);
                                }
                            });
                        }
                    });

                }

                @Override
                public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {

                }

                @Override
                public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                    LogUtil.i("onSurfaceTextureDestroyed-");
                    return false;
                }

                @Override
                public void onSurfaceTextureUpdated(SurfaceTexture surface) {

                }
            });
        }

//        mPlayer.setSurfaceTexture(videoView.getSurfaceTexture());
//        ThreadUtils.doOnThread(new ThreadUtils.ThreadTask() {
//            @Override
//            public void doOnThread() {
//                //此方法需要在子线程中执行
//                mPlayer.startRealPlay(play_url, new HikVideoPlayerCallback(){
//                    //播放结果回调
//                    // status 共三种状态：SUCCESS（播放成功）、FAILED（播放失败）、EXCEPTION（取流异常）
//                    // 错误码，只有 FAILED 和 EXCEPTION 才有值
//                    // 注意：回调仍为子线程
//                    @Override public void onPlayerStatus(@NonNull HikVideoPlayerCallback.Status status, int errorCode) {
//                    }
//                });
//            }
//        });
    }


    public void setSeleteView(boolean isSeleted) {
        if (isSeleted) {
            view_main.setBackgroundResource(R.drawable.video_seleted_bg);
        } else {
            view_main.setBackgroundColor(getResources().getColor(R.color.black));
        }
    }


    public void starPlay() {

    }


    public void pausePlay() {
    }

    public void stopPlay() {
        if(mPlayer != null){
            mPlayer.stopPlay();
        }
//        videoView.release(true);
//        videoView.setVideoURI(null);
//        videoView.stopPlayback();
    }

    public void resumPlay() {
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec),
                getDefaultSize(0, heightMeasureSpec));
        int childWidthSize = getMeasuredWidth();
        // 高度和宽度一样

        widthMeasureSpec = MeasureSpec.makeMeasureSpec(
                childWidthSize, MeasureSpec.EXACTLY);

//        heightMeasureSpec = childWidthSize/2*3;  //设定高是宽的比例
//        heightMeasureSpec = childWidthSize;  //设定高是宽的比例
        heightMeasureSpec = childWidthSize*240/375;  //设定高是宽的比例

        LayoutParams paramsViewMain;
        if (isFullSreen) {
//                        screenHeight = SystemParamsUtils.getScreenHeight();
//            screenWidth = SystemParamsUtils.getScreenWidth();
//
//            DisplayMetrics dm = getResources().getDisplayMetrics();
//            int x = dm.widthPixels;
//            int y = dm.heightPixels;

            DisplayMetrics outMetrics = new DisplayMetrics();
            ((Activity) getContext()).getWindowManager().getDefaultDisplay().getRealMetrics(outMetrics);
            int widthPixel = outMetrics.widthPixels;
            int heightPixel = outMetrics.heightPixels;

            screenWidth = widthPixel;
            screenHeight = heightPixel;

            if (screenWidth > screenHeight) {
                int temp = screenHeight;
                screenHeight = screenWidth;
                screenWidth = temp;
            }
            LogUtil.i("screenWidth---->" + screenWidth);
            LogUtil.i("screenHeight---->" + screenHeight);

            if (isBig) {
                paramsViewMain = new LayoutParams(screenHeight, screenWidth);
            } else {
                paramsViewMain = new LayoutParams(screenHeight / 2, screenWidth / 2);
            }

        } else {
            paramsViewMain = new LayoutParams(childWidthSize, heightMeasureSpec);
        }
        view_main.setLayoutParams(paramsViewMain);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    public boolean isFullSreen() {
        return isFullSreen;
    }

    public void setFullSreen(boolean fullSreen) {
        isFullSreen = fullSreen;
    }

    public boolean isBig() {
        return isBig;
    }

    public void setBig(boolean big) {
        isBig = big;
    }

    public void setParams(boolean big, boolean fulllSreen) {
        if (isFullSreen == fulllSreen && (isBig == big)) {
            return;
        }
        isBig = big;
        isFullSreen = fulllSreen;
        invalidate();
    }
}
